<template>
  <div class="user-detail-container" v-loading="loading">
    <div class="header">
      <el-page-header @back="goBack" :title="'返回用户列表'" :content="'用户详情 #' + userId" />
    </div>

    <el-card v-if="user" class="user-card">
      <template #header>
        <div class="card-header">
          <div class="user-info">
            <el-avatar :src="user.avatar" :size="80" />
            <div class="user-detail">
              <h2 class="username">{{ user.username }}</h2>
              <div class="nickname">{{ user.nickname }}</div>
              <div class="roles">
                <el-tag v-for="role in user.roles" :key="role" size="small" class="role-tag">
                  {{ getRoleName(role) }}
                </el-tag>
              </div>
            </div>
          </div>
          <el-tag :type="user.status === UserStatus.ENABLED ? 'success' : 'danger'">
            {{ user.status === UserStatus.ENABLED ? '启用' : '禁用' }}
          </el-tag>
        </div>
      </template>

      <el-descriptions :column="2" border>
        <el-descriptions-item label="用户ID">{{ user.id }}</el-descriptions-item>
        <el-descriptions-item label="用户名">{{ user.username }}</el-descriptions-item>
        <el-descriptions-item label="昵称">{{ user.nickname }}</el-descriptions-item>
        <el-descriptions-item label="邮箱">{{ user.email }}</el-descriptions-item>
        <el-descriptions-item label="手机号">{{ user.phone || '未设置' }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="user.status === UserStatus.ENABLED ? 'success' : 'danger'">
            {{ user.status === UserStatus.ENABLED ? '启用' : '禁用' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ user.createdAt }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ user.updatedAt }}</el-descriptions-item>
        <el-descriptions-item label="最后登录时间">{{ user.lastLoginAt || '未登录' }}</el-descriptions-item>
        <el-descriptions-item label="角色">
          <el-tag v-for="role in user.roles" :key="role" size="small" class="role-tag">
            {{ getRoleName(role) }}
          </el-tag>
        </el-descriptions-item>
      </el-descriptions>

      <div class="action-buttons">
        <el-button type="primary" @click="handleEdit">编辑用户</el-button>
        <el-button type="warning" @click="handleResetPassword">重置密码</el-button>
        <el-button
          :type="user.status === UserStatus.ENABLED ? 'danger' : 'success'"
          @click="handleStatusChange"
        >
          {{ user.status === UserStatus.ENABLED ? '禁用用户' : '启用用户' }}
        </el-button>
        <el-button type="danger" @click="handleDelete">删除用户</el-button>
      </div>
    </el-card>

    <!-- 重置密码对话框 -->
    <el-dialog v-model="resetPasswordDialogVisible" title="重置密码" width="500px">
      <el-form
        ref="resetPasswordFormRef"
        :model="resetPasswordForm"
        :rules="resetPasswordRules"
        label-width="100px"
      >
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="resetPasswordForm.newPassword" type="password" placeholder="请输入新密码" show-password />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="resetPasswordDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitResetPasswordForm">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { getUserDetail, deleteUser, updateUserStatus, resetPassword } from '@/api/system/user.ts';
import { UserStatus, UserRole, type User, type ResetPasswordRequest } from '@/types/system/user.ts';
import type { FormInstance } from 'element-plus';

const route = useRoute();
const router = useRouter();
const userId = ref(route.query.id as string);

// 用户数据
const user = ref<User | null>(null);
const loading = ref(false);

// 重置密码对话框
const resetPasswordDialogVisible = ref(false);
const resetPasswordFormRef = ref<FormInstance>();
const resetPasswordForm = reactive<ResetPasswordRequest>({
  userId: parseInt(userId.value),
  newPassword: ''
});

// 重置密码校验规则
const resetPasswordRules = {
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ]
};

// 获取用户详情
const getUserInfo = async () => {
  if (!userId.value) {
    ElMessage.error('用户ID不能为空');
    return;
  }

  loading.value = true;
  try {
    const res = await getUserDetail(parseInt(userId.value));
    user.value = res.data;
  } catch (error) {
    console.error('获取用户详情失败', error);
    ElMessage.error('获取用户详情失败');
  } finally {
    loading.value = false;
  }
};

// 获取角色名称
const getRoleName = (roleCode: string) => {
  switch (roleCode) {
    case UserRole.ADMIN:
      return '管理员';
    case UserRole.DEVELOPER:
      return '开发者';
    case UserRole.USER:
      return '普通用户';
    default:
      return roleCode;
  }
};

// 返回列表
const goBack = () => {
  router.push('/user-management/users');
};

// 编辑用户
const handleEdit = () => {
  router.push({ path: '/user-management/users/edit', query: { id: userId.value } });
};

// 删除用户
const handleDelete = async () => {
  if (!user.value) return;

  try {
    await ElMessageBox.confirm(`确定要删除用户 ${user.value.username} 吗？`, '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    await deleteUser(user.value.id);
    ElMessage.success('删除用户成功');
    router.push('/user-management/users');
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('删除用户失败', error);
      ElMessage.error('删除用户失败');
    }
  }
};

// 修改用户状态
const handleStatusChange = async () => {
  if (!user.value) return;

  const newStatus = user.value.status === UserStatus.ENABLED ? UserStatus.DISABLED : UserStatus.ENABLED;
  const statusText = newStatus === UserStatus.ENABLED ? '启用' : '禁用';

  try {
    await ElMessageBox.confirm(`确定要${statusText}用户 ${user.value.username} 吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    await updateUserStatus(user.value.id, newStatus);
    ElMessage.success(`${statusText}用户成功`);
    getUserInfo();
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error(`${statusText}用户失败`, error);
      ElMessage.error(`${statusText}用户失败`);
    }
  }
};

// 重置密码
const handleResetPassword = () => {
  resetPasswordForm.newPassword = '';
  resetPasswordDialogVisible.value = true;
};

// 提交重置密码表单
const submitResetPasswordForm = async () => {
  if (!resetPasswordFormRef.value) return;

  await resetPasswordFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await resetPassword(resetPasswordForm);
        ElMessage.success('重置密码成功');
        resetPasswordDialogVisible.value = false;
      } catch (error) {
        console.error('重置密码失败', error);
        ElMessage.error('重置密码失败');
      }
    }
  });
};

onMounted(() => {
  getUserInfo();
});
</script>

<style scoped>
.user-detail-container {
  padding: 20px;
}

.header {
  margin-bottom: 20px;
}

.user-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.user-info {
  display: flex;
  align-items: center;
}

.user-detail {
  margin-left: 20px;
}

.username {
  margin: 0 0 5px 0;
}

.nickname {
  font-size: 16px;
  color: #666;
  margin-bottom: 10px;
}

.roles {
  display: flex;
  gap: 5px;
}

.role-tag {
  margin-right: 5px;
}

.action-buttons {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
